package com.uzai.console.config;

import com.uzai.trace.TraceIdThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author jianghan
 * @date 2017-11-09 17:01
 */
@Configuration
public class TaskExecutorConfig {
    private int corePoolSize = 200;
    private int maxPoolSize = 500;
    private int queueCapacity = 10240;
    private int keepAlive = 200;

    @Bean
    public TaskExecutor taskExecutor() {
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(corePoolSize);
//        executor.setMaxPoolSize(maxPoolSize);
//        executor.setQueueCapacity(queueCapacity);
//        executor.setThreadNamePrefix("console-task-");
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        executor.setKeepAliveSeconds(keepAlive);
//        executor.initialize();

        TraceIdThreadPoolExecutor executor = new TraceIdThreadPoolExecutor(corePoolSize, maxPoolSize, keepAlive, TimeUnit.MINUTES, new LinkedBlockingQueue<>(queueCapacity));
        executor.setThreadFactory(new CustomizableThreadFactory("console-task-"));
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
